#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_icon=favicon.ico
#AutoIt3Wrapper_Compression=4
#AutoIt3Wrapper_Res_Fileversion=1.0.0.10
#AutoIt3Wrapper_Res_Fileversion_AutoIncrement=y
#AutoIt3Wrapper_Res_LegalCopyright=John Seekins
#AutoIt3Wrapper_Res_Description=System Restore Utility
#AutoIt3Wrapper_Res_Language=1033
#AutoIt3Wrapper_Res_requestedExecutionLevel=requireAdministrator
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#comments-start
Copyright (c) <2011>, <John Seekins>
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#comments-end
#include <GUIConstants.au3>

Opt("TrayIconHide", 1)

#Region Global Variables
Dim $programTitle = "System Restore Utility"
Dim $CurX = 30
Dim $CurY = 10
Dim $imageFileName = IniRead("restore.ini", "Global", "restoreImageName", "initial.wim")

Dim $fixedDrives = DriveGetDrive("FIXED")
For $i = 1 To $fixedDrives[0]
	$fixedDrives[$i] = StringUpper($fixedDrives[$i])
Next
Dim $destinationDrive = ""
For $i = 1 To $fixedDrives[0]
	If DriveGetLabel($fixedDrives[$i]) = "SYSTEM" Then $destinationDrive = $fixedDrives[$i]
Next
If $destinationDrive = "" Then
	For $i = 1 To $fixedDrives[0]

	Next
EndIf
Dim $opticalDrives = DriveGetDrive("CDROM")
Dim $sourceDrive = ""
For $i = 1 To $opticalDrives[0]
	If DriveGetLabel($opticalDrives[$i]) = "IMAGEX" Then $sourceDrive = $opticalDrives[$i]
Next
Dim $imageFileLoc = $sourceDrive & "\" & $imageFileName
#EndRegion Global Variables

$hGUI = GUICreate($programTitle, 250, 175)
Opt("GUICoordMode", 1)

#Region Drop-Down Menu
$fileMenu = GUICtrlCreateMenu("&File")
$exitProgramMenuItem = GUICtrlCreateMenuItem("E&xit", $fileMenu)
$helpMenu = GUICtrlCreateMenu("&Help")
$aboutMenuItem = GUICtrlCreateMenuItem("About...", $helpMenu)
#EndRegion Drop-Down Menu

#Region Main Restore Console
GUICtrlCreateGroup("Restore Functions", $CurX - 15, $CurY, 225, 90)
$CurY += 25
$restoreSystemButton = GUICtrlCreateButton("  Restore System To Factory Defaults  ", $CurX, $CurY)
$CurY += 35
$formatDrive = GUICtrlCreateCheckbox("Format System Drive?", $CurX + 23, $CurY)
$CurY += 45
$checkDiskButton = GUICtrlCreateButton("  Test Physical Drives For Errors  ", $CurX + 10, $CurY)
#EndRegion Main Restore Console

GUISetState()

;Hide calling window
modCallingWindow("startnet.cmd", @SW_MINIMIZE)

Do
	$msg = GUIGetMsg()
	Switch $msg
		Case $aboutMenuItem
			MsgBox(0, $programTitle, "Version: " & FileGetVersion("Restore.exe"))

		Case $checkDiskButton
			MsgBox(64, "Disk Check", "Beginning physical disk testing and repair of all Physical Drives", 5)
			For $i = 1 To $fixedDrives[0]
				$sCmd = @ComSpec & " /c chkdsk " & $fixedDrives[$i] & " /r"
				$ret = RunWait($sCmd, @ScriptDir, @SW_SHOW)
				If $ret <> 1 Then
					SplashTextOn("Return Code", "Disk testing failed with code: " & @error, 400, 200, -1, -1, 32, "Tahoma", 16, 500)
					Sleep(3000)
					SplashOff()
				Else
					MsgBox(64, "Disk Check", "Finished physical disk testing and repair...", 5)
				EndIf
			Next

		Case $restoreSystemButton
			doApply()

		Case $exitProgramMenuItem
			$msg = $GUI_EVENT_CLOSE
	EndSwitch
Until $msg = $GUI_EVENT_CLOSE

modCallingWindow("startnet.cmd", @SW_RESTORE)
GUIDelete()

Func doApply()
	Local $bootsecType = ""
	Local $applySource = ""
	Local $applyDestination = ""
	Local $applyName = ""

	If MsgBox(20, "Stop!", "This program can severely damage your system, possibly destroying all data on it!" & @LF & "Would you like to continue?") = 6 Then
		If (FileExists($imageFileLoc)) AND (StringRight($applySource, 4) = ".wim") Then
			If GUICtrlRead($formatDrive) = 1 Then
				$sCmd = "format.com " & $applyDestination & " /Q /Y"
				$ret = RunWait($sCmd, @WorkingDir, @SW_SHOW)
				If $ret <> 0 Then
					SplashTextOn("Format Failed!", "Format.com failed with code: " & @error, 400, 200, -1, -1, 32, "Tahoma", 16, 500)
					Sleep(3000)
					SplashOff()
					Return 0
				EndIf
			EndIf

			$sCmd = "imagex.exe /apply /verify " & $applySource & " " & $applyName & " " & $applyDestination

			$ret = RunWait($sCmd, @WorkingDir, @SW_SHOW)
			If $ret <> 0 Then
				SplashTextOn("Imaging Failed!", "Imagex.exe failed with code: " & @error, 400, 200, -1, -1, 32, "Tahoma", 16, 500)
				Sleep(3000)
				SplashOff()
				Return 0
			EndIf

			If GUICtrlRead($formatDrive) = 1 Then
				If FileExists($applyDestination & "\boot.ini") Then
					$bootsecType = "/nt52"
				Else
					$bootsecType = "/nt60"
				EndIf

				$ret = RunWait("bootsect.exe " & $bootsecType & " /force " & $applyDestination, @WindowsDir, @SW_HIDE)
				If $ret <> 0 Then
					SplashTextOn("Boot Sector writing failed!", $applyDestination & " boot sector re-write failed with code: " & @error, 400, 200, -1, -1, 32, "Tahoma", 16, 500)
					Sleep(3000)
					SplashOff()
					Return 0
				EndIf
				$ret = RunWait("bootsect.exe " & $bootsecType & " SYS /mbr", @WindowsDir, @SW_HIDE)
				If $ret <> 0 Then
					SplashTextOn("Master Boot Record writing failed!", "MBR Re-write failed with code: " & @error, 400, 200, -1, -1, 32, "Tahoma", 16, 500)
					Sleep(3000)
					SplashOff()
					Return 0
				EndIf
			EndIf
			Return 1 ; success
		Else
			MsgBox(48, "Invalid image!", "Image " & $applySource & " does not exist or is an improperly formatted .wim file!")
			Return 0
		EndIf
	EndIf
EndFunc

Func IsVisible($handle)
	If BitAND(WinGetState($handle), 2) Then
		Return 1
	Else
		Return 0
	EndIf
EndFunc   ;==>IsVisible

Func modCallingWindow($title, $state)
	Local $activeWindowList = WinList()
	Local $windowNumber = 0
	For $i = 1 To $activeWindowList[0][0]
		If $activeWindowList[$i][0] <> "" And IsVisible($activeWindowList[$i][1]) Then
			Local $windowTitle = StringTrimLeft($activeWindowList[$i][0], StringLen($activeWindowList[$i][0]) - StringLen($title))
			If $windowTitle = $title Then
				$windowNumber = $i
				WinSetState($activeWindowList[$i][0], "", $state)
			EndIf
		EndIf
	Next
EndFunc   ;==>modCallingWindow
